package com.yy.cleaner.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yy.cleaner.mapper.UserMapper;
import com.yy.cleaner.model.pojo.LoginUser;
import com.yy.cleaner.model.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 创建一个类实现UserDetailsService接口，重写其中的方法。
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    /**
     * 定义自己的UserDetails实现方法
     * 1.通过数据库查表
     * 2.若查到用户信息 则将 数据封装到到UserDetails 返回
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中
        //封装成UserDetails对象返回
        return new LoginUser(user);
    }
}
